<template>
  <div class="system-sports">
    <iframe v-if="loading && !piniaSystem.getIsH5" :src="getBase64Url(mp4pc)" frameborder="0" width="100%" height="702" scrolling="no" allow="autoplay; fullscreen"></iframe>
    <iframe v-if="loading && piniaSystem.getIsH5" :src="getBase64Url(mp4h5)" frameborder="0" width="414" height="800" scrolling="no" allow="autoplay; fullscreen"></iframe>
    <div id="betby"></div>
  </div>
  <CurrencyExchange
    v-model:playId="playId"
    v-model:visible="showCurrencyExchange"
    @queryThirdUrl="getSportsGame"
  />
</template>

<script setup lang="ts">
import userinfo from '@/store/userinfo';
import system from '@/store/system';
import sportsApi from '@/api/modules/sports';
import gamesApi from '@/api/modules/games';
import { isDark } from '@/utils/dark';
import { loadVoLteResourceList } from '@/utils/format';
import router from '@/router';

const mp4h5 = new URL('../../assets/Sport_h5.mp4', import.meta.url).href;
const mp4pc = new URL('../../assets/Sport.mp4', import.meta.url).href;

const piniaUserinfo:any = userinfo();
const piniaSystem:any = system();
const { t } = useI18n();
const route = useRoute();

const data: any = reactive({
  loading: true,
  src: "",
  playId: computed(()=>piniaUserinfo.getSportsInfo.playId),
  showCurrencyExchange: false,
  btRenderer: null,
});

const {
  loading,
  src,
  playId,
  showCurrencyExchange,
  btRenderer,
} = toRefs(data);

// 初始化运动
const getSportsGame = () => {
  let params = {
    playId: playId.value,
    currencyId: piniaUserinfo.getCurrentWallet.currencyId,
    language: piniaSystem.getLang.locale || 'en',
    lobbyUrl: `https://${window.location.host}`,
    ifRate: 0,
    deviceType: piniaSystem.getIsH5 ? 2 : 1
  }
  if(params.language){
    sportsApi.thirdUrl(params).then((response: any) => {
      console.log(response, '運動初始化---------------');
      if(response.code === 200){
        loading.value = false;
        if(response.data == "code_1131"){
          // 默认货币不足
          gamesApi.getGameRateList({
            playId: playId.value,
            currencyId: piniaUserinfo.getCurrentWallet.currencyId,
          }).then((response: any) => {
            console.log("货币不足, 查询可兑换货币", response)
            if(response.code === 200 && response.data.list && response.data.list.length > 0){
              // 默认货币不足
              showCurrencyExchange.value = true;
            }
          });
        }else{
          src.value = response.msg;
          initailize();
        }
      }else{
        router.replace({
          path: "/home"
        });
      }
    })
  }
}

// 动态加载js
loadVoLteResourceList([
  "https://ui.invisiblesport.com/bt-renderer.min.js",
]).then(()=>{
  // 牌照
  console.log('运动jdk加载成功')
  getSportsGame();
}).catch((e)=>{
  console.log("运动JDK加载失败", e)
});

const getQuerys = (url: string) => {
  if (url) {
    const queryString = url.split("?")[1];
    return queryString.split("&").reduce((acc:any, cur:any) => {
      const [key, val] = cur.split("=");
      acc[key] = val;
      return acc;
    }, {});
  } else {
    return {};
  }
}

// 重置token
const resetToken = () => {
  return new Promise((resolve, reject) => {
    let params = {
      playId: playId.value,
      currencyId: piniaUserinfo.getCurrentWallet.currencyId,
      language: piniaSystem.getLang.locale || 'en',
      lobbyUrl: `https://${window.location.host}`,
      ifRate: 0,
      deviceType: piniaSystem.getIsH5 ? 2 : 1
    }
    if(params.language){
      sportsApi.thirdUrl(params).then((response: any) => {
        console.log(response, 'res---------------');
        if(response.code === 200){
          resolve(getQuerys(response.msg).token);
        }else{
          reject()
        }
      })
    }
  });
}

// 重新登陆
const reLoginSports = () => {
  btRenderer.value && btRenderer.value.kill();
  getSportsGame();
}

// 初始化显示
const initailize = () => {
  btRenderer.value && btRenderer.value.kill();
  let queryDatas = getQuerys(src.value);
  console.log(queryDatas)
  btRenderer.value = new (window as any).BTRenderer().initialize({
    brand_id: queryDatas.brand_id,
    token: queryDatas.token || null,
    // themeName: "demo-blue-dark-sidebar",
    themeName: isDark.value ? 'openbox' : 'openbox-light',
    // themeName: 'openbox',
    lang: queryDatas.lang || "en",
    target: document.getElementById("betby"),
    betSlipOffsetTop: 130,
    betslipZIndex: 10,
    fontFamilies: ["Montserrat, sans-serif", "Roboto, sans-serif"],
    url: route.query.url ? `/${route.query.url}` : '' ,
    onTokenExpired: () => {return resetToken()},
    onRouteChange: () => { },
    onLogin: () => { },
    onRegister: () => { },
    onSessionRefresh: () => {reLoginSports()},
    // onBetSlipStateChange: (data) => { _this.handleSlipChange(data) },
    // onBannerClick: () => { },
    onRecharge: ()=>{ showCurrencyExchange.value = true;}
  });
}


// --- 获取mp4
const getBase64Url = (url: string) => {
  const content = `<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <style>
        *{
          margin: 0;
          padding: 0;
        }
      </style>
    </head>
    <body>
      <video src="${url}" autoplay="true" loop></video>
    </body>
  </html>`;
  return `data:text/html;base64,${btoa(content)}`
}

</script>

<style lang="scss" scoped>
@import url(./index.scss);
</style>
